"""
MCP上下文模型

用于存储MCP会话的上下文数据
"""

from sqlalchemy import Column, String, Boolean, Integer, DateTime, JSON, Text, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.database import Base
import enum


class ContextType(str, enum.Enum):
    """上下文类型枚举"""
    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"
    TOOL = "tool"


class MCPContext(Base):
    """
    MCP上下文表
    
    存储MCP会话的上下文数据，支持版本管理
    """
    __tablename__ = "mcp_contexts"
    
    # 主键
    id = Column(Integer, primary_key=True, index=True, autoincrement=True, comment="主键")
    
    # 会话关联
    session_id = Column(String(128), ForeignKey("mcp_sessions.session_id", ondelete="CASCADE"), nullable=False, index=True, comment="MCP会话ID")
    
    # 上下文数据
    model_id = Column(String(128), comment="模型ID")
    context_data = Column(JSON, nullable=False, comment="上下文数据（JSON格式）")
    context_type = Column(
        Enum(ContextType),
        default=ContextType.USER,
        nullable=False,
        index=True,
        comment="上下文类型"
    )
    
    # 元数据
    context_metadata = Column(JSON, comment="元数据")
    version = Column(Integer, default=1, nullable=False, comment="版本号")
    
    # 统计信息
    token_count = Column(Integer, default=0, nullable=False, comment="Token数量")
    size_bytes = Column(Integer, default=0, nullable=False, comment="数据大小（字节）")
    
    # 加密标记
    is_encrypted = Column(Boolean, default=False, nullable=False, comment="是否加密")
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True, comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")
    
    # 关系
    session = relationship("MCPSession", back_populates="contexts")
    
    def __repr__(self):
        return f"<MCPContext(id={self.id}, session_id={self.session_id}, type={self.context_type}, version={self.version})>"

